#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>

void usage(char* pname) {
  printf("Usage: %s <r|w> <r|w>\n", pname);
  exit(-1);
}

pthread_rwlock_t rwlock;

void *th_fn(void* arg) {
  char *rw = (char*)arg;
  int err;
  if (!strcmp("r", rw)) {
    if ((err = pthread_rwlock_rdlock(&rwlock)) != 0) {
      printf("second read lock: %s\n", strerror(err));
    }
    else {
      puts("second read lock success");
    }
  }
  else if (!strcmp("w", rw)) {
    if ((err = pthread_rwlock_wrlock(&rwlock)) != 0) {
      printf("second write lock: %s\n", strerror(err));
    }
    else {
      puts("second write lock success");
    }
  }
  else {
    usage(rw);
  }
  pthread_rwlock_unlock(&rwlock);
}

int main(int argc, char *argv[]) {
  if (argc < 3) {
    usage(argv[0]);
  }
  int err;

  
  pthread_rwlock_init(&rwlock, NULL);

  if (!strcmp("r", argv[1])) {
    if ((err = pthread_rwlock_rdlock(&rwlock)) != 0) {
      printf("first read lock: %s\n", strerror(err));
    }
    else {
      puts("first read lock success");
    }
  }
  else if (!strcmp("w", argv[1])) {
    if ((err = pthread_rwlock_wrlock(&rwlock)) != 0) {
      printf("first write lock: %s\n", strerror(err));
    }
    else {
      puts("first write lock success");
    }
  }
  else {
    usage(argv[0]);
  }

  pthread_t tid;
  pthread_create(&tid, NULL, th_fn, (void*)argv[2]);
  pthread_join(tid, NULL);

  pthread_rwlock_unlock(&rwlock);
  return 0;
}
